// 展示给用户 负载均衡式地调用compile_server
#include <iostream>
#include <signal.h>
#include "../comm/httplib.h"
#include "oj_control.hpp"
using namespace httplib;
using namespace ns_control;

static Control *ctl_ptr = nullptr;

void Recovery(int signal)
{
    ctl_ptr->RecoveryMachine();
}

int main()
{
    signal(SIGQUIT, Recovery);
    Server svr;
    Control ctl;
    ctl_ptr = &ctl;

    // 1.获取题目列表
    // 返回一张包含所有题目信息的html网页
    svr.Get("/all_questions", [&ctl](const Request &req, Response &resp)
            { 
                std::string html;
                ctl.AllQuestions(&html);
                resp.set_content(html, "text/html; charset=utf-8"); });
    // resp.set_content("这是所有题目的列表", "text/plain; charset=utf-8"); });

    // 2.用户根据题目编号，获取题目内容
    // R"()" 原始字符串raw string 保持字符串的原貌 不用自己做转义
    // /question/100 -> 正则匹配
    svr.Get(R"(/question/(\d+))", [&ctl](const Request &req, Response &resp)
            { 
                std::string number=req.matches[1];
                std::string html;
                ctl.Question(number,&html);
                resp.set_content(html, "text/html; charset=utf-8"); });
    // 3.用户提交代码，使用判题功能(1.测试用例2.compile_and_run)
    svr.Post(R"(/judge/(\d+))", [&ctl](const Request &req, Response &resp)
             {
                std::string number=req.matches[1];
                std::string result_json;
                std::string in_json=req.body;
                ctl.Judge(number,in_json,&result_json);
                resp.set_content(result_json,"application/json; charset=utf-8"); });
    // resp.set_content("题目"+number, "text/plain; charset=utf-8"); });
    svr.set_base_dir("./wwwroot"); // 默认的首页
    svr.listen("0.0.0.0", 8080);
    return 0;
}